package com.shebao.utils;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import java.io.IOException;

/**
 * PDF 每页的页脚
 *
 * Created by Administrator on 2017\12\22 0022.
 */
public class PDFPageHelperPerson extends PdfPageEventHelper {

    protected float startpos = -1;
    protected Font bfFont;

    protected int totalPage;

    public PDFPageHelperPerson(int totalPage) {
        this.totalPage = totalPage;
    }

    @Override
    public void onOpenDocument(PdfWriter writer, Document document) {
        try {
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            bfFont = new Font(bfChinese,9,Font.NORMAL);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        super.onOpenDocument(writer, document);
    }

    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        //在每页结束的时候把“第x页”信息写道模版指定位置
//        PdfContentByte cb = writer.getDirectContent();
//        cb.saveState();
//        String text = "第" + writer.getPageNumber() + "页,共";
//        cb.beginText();
//        cb.setFontAndSize(bf, 8);
//        //定位“第x页,共” 在具体的页面调试时候需要更改这xy的坐标
//        cb.setTextMatrix(460, 786);
//        cb.showText(text);
//        cb.endText();
//        //定位“y页” 在具体的页面调试时候需要更改这xy的坐标
//        cb.addTemplate(tpl,  492, 786);
//
//        cb.saveState();
//        cb.stroke();
//        cb.restoreState();
//        cb.closePath();//sanityCheck();



        //所有页
        Rectangle pagesize = document.getPageSize();

        //当前页显示
        String text = "第" + writer.getPageNumber() + "页              ,  共"+totalPage+"页";
        Phrase phrase = new Phrase(text,bfFont);
        ColumnText.showTextAligned(
                writer.getDirectContent(),
                Element.ALIGN_LEFT,
                phrase,
                (pagesize.getLeft() + pagesize.getRight()) / 2-50,
                pagesize.getBottom() + 20,
                0);
        if (startpos != -1){
            onParagraphEnd(writer, document, pagesize.getBottom(document.bottomMargin()));
        }
        startpos = pagesize.getTop(document.topMargin());
    }

    @Override
    public void onCloseDocument(PdfWriter writer, Document document) {
        //关闭document的时候获取总页数，并把总页数按模版写道之前预留的位置
//        tpl.beginText();
//        tpl.setFontAndSize(bf, 8);
//        tpl.showText(Integer.toString(writer.getPageNumber() - 1)+"页");
//        tpl.endText();
//        tpl.closePath();
    }
}
